package subcommands

import (
	"fmt"
	"rc/config"
	"rc/logger"

	flags "github.com/jessevdk/go-flags"
	"github.com/urfave/cli"
)

func SetCli(c *cli.Context) error {
	return setOpts(c.String("r"),
		c.String("l"),
		c.String("t"),
		c.String("p"),
		c.Int("e"),
		c.Int("b"))
}

func Set(args []string) error {
	var (
		err error
		log = logger.GetLogger()
	)

	// opts for login subcommand
	var opts struct {
		RepoPath    string `short:"r" long:"repo" description:"set repo path"`
		LogLevel    string `short:"l" long:"logLevel" description:"set log level(ex. debug warn error)"`
		LogType     string `short:"t" long:"logType" description:"set log type(ex. console file)"`
		LogPath     string `short:"p" long:"logPath" description:"set log path"`
		ExecTimeout int    `short:"e" long:"execTimeout" description:"set exec timeout, unit(second)"`
		BufferSize  int    `short:"b" long:"bufferSize" description:"set buffer size for transfer files, unit()"`
	}

	var parser = flags.NewParser(&opts, flags.HelpFlag|flags.PassDoubleDash)
	parser.Command.Name = "set" // set current command name
	_, err = parser.ParseArgs(args)
	if err != nil {
		if err.(*flags.Error).Type == flags.ErrHelp {
			fmt.Println(err.Error())
			return nil
		}
		log.Debug("parser error : %#v\n", err)
		return err
	}
	log.Debug("opts: %v\n", opts)

	return setOpts(opts.RepoPath,
		opts.LogLevel,
		opts.LogType,
		opts.LogPath,
		opts.ExecTimeout,
		opts.BufferSize)
}

func setOpts(repoPath, logLevel, logType, logPath string, execTimeout, bufferSize int) error {
	var (
		err   error
		cfg   = config.GetConfig()
		log   = logger.GetLogger()
		isSet = false
	)

	// set repo path
	if repoPath != "" {
		isSet = true
		err = cfg.SetRepoPath(repoPath)
	}
	if err != nil {
		return err
	}

	// set logger
	if logLevel != "" || logType != "" || logPath != "" {
		isSet = true
		err = cfg.SetLogger(logLevel, logType, logPath)
	}
	if err != nil {
		return err
	}

	// set exec timeout
	log.Debug("exec timeout: %d\n", execTimeout)
	if execTimeout > 0 {
		isSet = true
		err = cfg.SetExecTimeout(execTimeout)
	}
	if err != nil {
		return err
	}

	// set buffer size
	if bufferSize > 0 {
		isSet = true
		err = cfg.SetBufferSize(bufferSize)
	}
	if err != nil {
		return err
	}

	if !isSet {
		cfg.DisplayConfig()
	}

	return err
}
